# 二次封装定位元素的方法
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time   : 2023/05
# @Author : Renee

from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
import selenium

class BasePage:

    def __init__(self, driver):
        self.driver = driver

        # print(dir(driver))
    # 元素定位，替代八大定位

    def get_element(self, element):
        try:
            _type = element[0]
            value = element[1]
            if type == "id" or type == "ID" or type == "Id":
                elem = self.driver.find_element(By.ID, value)
            elif type == "name" or type == "NAME" or type == "Name":
                elem = self.driver.find_element(By.NAME, value)
            elif type == "class" or type == "CLASS" or type == "Class":
                elem = self.driver.find_element(By.CLASS_NAME, value)
            elif type == "link" or type == "LINK" or type == "link":
                elem = self.driver.find_element(By.CLASS_NAME, value)
            elif type == "xpath" or type == "xpath" or type == "Xpath":
                elem = self.driver.find_element(By.XPATH, value)
            elif type == "css" or type == "CSS" or type == "Css":
                elem = self.driver.find_element(By.CSS_SELECTOR, value)
            else:
                raise NameError("Please input correct the type parameter!")
        except Exception:
            raise NameError("This element not found!" + str(element))
        return elem

    # 点击
    def left_click(self, *locator):
        ActionChains(self.driver).click(self.get_element(*locator)).perform()

    # 输入
    def send_text(self, text, *locator):
        return self.driver.find_element(*locator).send_keys(text)

    # 清空
    def clear_text(self, *locator):
        self.driver.find_element(*locator).clear()

    # 切换表单
    def switch_iframe(self, *locator):
        self.driver.swich_to.frame(self.driver.find_element(*locator))

    # 跳出表单
    def default_switch(self):
        return self.driver.switch_to.default_content()

    # 切换窗口
    def switch_window(self, n):
        self.driver.switch_to.window(self.driver.window_handles[n])

    # 用于断言（元素属性、页面标题、当前网址、标签信息）
    def get_attribute_value(self, name, *locator):
        return self.get_element(*locator).get_attribute(name)

    def get_title(self):
        return self.driver.title

    def get_current_url(self):
        return self.driver.current_url

    def get_element_text(self, *locator):
        return self.driver.find_element(*locator).text

    def quit(self):
        return self.driver.quit()

    def wait(self, sec):
        return self.driver.implicitly_wait(sec)
